package com.example.bbs.ui.tool;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bbs.R;

public class RecyclerAdapterLoadMoreWrapper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static class FootViewHolder extends RecyclerView.ViewHolder {

        LinearLayout llLoading;
        LinearLayout llEnd;
        LinearLayout llBlank;

        FootViewHolder(View itemView) {
            super(itemView);
            llLoading = itemView.findViewById(R.id.ll_loading);
            llEnd = itemView.findViewById(R.id.ll_end);
            llBlank = itemView.findViewById(R.id.ll_blank);
        }

        void setDisplayType(int loadState) {
            llLoading.setVisibility(loadState == LOADING ? View.VISIBLE : View.GONE);
            llEnd.setVisibility(loadState == LOADING_END ? View.VISIBLE : View.GONE);
            // 加载完成后，也需要一段空白，保持高度一致。否则，下滑的时候会出现滑不下去的情况。
            llBlank.setVisibility(loadState == LOADING_COMPLETE ? View.VISIBLE : View.GONE);
        }
    }

    abstract public static class ReachBottomOnScrollListener extends RecyclerView.OnScrollListener {

        private boolean mSlidingUpward = false; // 用来标记是否正在向上滑动

        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);

            LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
            if (newState == RecyclerView.SCROLL_STATE_IDLE && manager != null) {
                int lastItemPosition = manager.findLastCompletelyVisibleItemPosition();
                int itemCount = manager.getItemCount();

                if (lastItemPosition >= itemCount - 3 && mSlidingUpward) {
                    onLoadMore();
                }
            }
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            mSlidingUpward = dy > 0;
        }

        public abstract void onLoadMore();
    }

    public static final int LOADING = 1;
    public static final int LOADING_COMPLETE = 2;
    public static final int LOADING_END = 3;
    static final String LOG_TAG = RecyclerAdapterLoadMoreWrapper.class.getSimpleName();
    static final int TYPE_ITEM = 1;
    static final int TYPE_FOOTER = 2;

    public int mLoadState = LOADING_COMPLETE;
    final RecyclerView.Adapter<RecyclerView.ViewHolder> mAdapter;

    public RecyclerAdapterLoadMoreWrapper(RecyclerView.Adapter<RecyclerView.ViewHolder> adapter) {
        this.mAdapter = adapter;
    }

    @Override
    public int getItemViewType(int position) {
        if (position + 1 == getItemCount()) {
            return TYPE_FOOTER;
        } else {
            return TYPE_ITEM;
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        //进行判断显示类型，来创建返回不同的View
        if (viewType == TYPE_FOOTER) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.view_refresh, parent, false);
            return new FootViewHolder(view);
        } else {
            return mAdapter.onCreateViewHolder(parent, viewType);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof FootViewHolder ) {
            ((FootViewHolder) holder).setDisplayType(mLoadState);
        } else {
            mAdapter.onBindViewHolder(holder, position);
        }
    }

    @Override
    public int getItemCount() {
        return mAdapter.getItemCount() + 1;
    }

    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);

        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager instanceof GridLayoutManager) {
            final GridLayoutManager gridManager = ((GridLayoutManager) manager);
            gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    // 如果当前是footer的位置，那么该item占据2个单元格，正常情况下占据1个单元格
                    return getItemViewType(position) == TYPE_FOOTER ? gridManager.getSpanCount() : 1;
                }
            });
        }
    }

    /**
     * 设置上拉加载状态
     * @param loadState 1.正在加载 2.加载完成 3.加载到底
     */
    public void setLoadState(int loadState) {
        Log.d(LOG_TAG, "start change state");
        this.mLoadState = loadState;
        notifyItemChanged(getItemCount() - 1);
        Log.d(LOG_TAG, "Load State Changed, count: " + getItemCount() + " state: " + loadState);
    }

    public int getLoadState() {
        return mLoadState;
    }
}
